/*
 * Copyright (c) 2006 Freebookie
 */
package org.bookie.framework;

import org.apache.tapestry.IMarkupWriter;
import org.apache.tapestry.IRequestCycle;
import org.apache.tapestry.binding.ExpressionBinding;
import org.apache.tapestry.form.IFormComponent;
import org.apache.tapestry.form.validator.Required;
import org.apache.tapestry.form.validator.Validator;
import org.apache.tapestry.valid.IValidator;
import org.apache.tapestry.valid.ValidationDelegate;

/**
 * Custom gelegate - put a "*" sign behind required fields and mark errorneous
 * fields with red "*" sign and specific style
 * 
 * @author zubairov
 * @version 1.0, Apr 18, 2006
 * @see
 * @since
 * 
 * <pre>
 *  Revision History :
 *  VERSION	DATE			AUTHOR			COMMENT
 *  1.0		Apr 18, 2006		zubairov
 * </pre>
 */
public class CustomDelegate extends ValidationDelegate
{

	/**
	 * Generated serial version UID
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * Writes a "*" sign after required fields. If required fiels has error then
	 * "*" sign is written in red color.
	 */
	public void writeSuffix( IMarkupWriter writer,
			IRequestCycle cycle,
			IFormComponent component,
			IValidator validator )
	{
		boolean required = isRequired(component);
		boolean error = isInError();
		if (required && !error)
		{
			writer.printRaw("&nbsp;");
			writer.print("*");
		}

		if( required && error )
		{
			writer.printRaw("&nbsp;");
			writer.begin("font");
			writer.attribute("color", "red");
			writer.print("*");
			writer.end();
		}
	}

	/**
	 * Returns if component is required
	 * 
	 * @param component
	 * @return
	 */
	private boolean isRequired( IFormComponent component )
	{
		boolean requiredField = component.isRequired();
		if( component.getBinding("validators") instanceof ExpressionBinding )
		{
			ExpressionBinding expressionBinding = (ExpressionBinding)component.getBinding("validators");
			Validator singleValidator = (Validator)expressionBinding.getObject();
			if( singleValidator instanceof Required || singleValidator.isRequired() )
			{
				requiredField = true;
			}
		}
		return requiredField;
	}

	/**
	 * Writes additional attributes to the input fields.
	 */
	public void writeAttributes( IMarkupWriter writer,
			IRequestCycle cycle,
			IFormComponent comp,
			IValidator validator )
	{
		boolean required = isRequired(comp);
		boolean error = isInError();
		if (required) {
			if (error) {
				writer.attribute("class", "error");
			} else {
				writer.attribute("class", "required");				
			}
		} else {
			if (error) writer.attribute("class", "error");
		}
	}

}
